package evan.zhang.flags;


import java.io.IOException;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.readystatesoftware.mapviewballoons.BalloonOverlayView;

import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;


public class FlagsMapActivity extends MapActivity {
	
/**************************************************************************/
	private final static String tag = "FlagsOnMap::MyMapActivity";
    private MapView mapView;
    public MapView getMapView() {
    	return this.mapView;
    }
    private FlagsContext flagsContext;
    private FlagsBalloonItemizedOverlay flagsOverlay;
    
    private Flags flags;
   // private BalloonOverlayView balloonView;
    
    private ProgressDialog searchDialog;
    private ProgressDialog loadDialog;
/**************************************************************************/     
/*    
    public void setupDistBoundaryOverlay() {
		distBoundaryOverlay overlayChina = new distBoundaryOverlay("China",this);
		mapOverlays.add(overlayChina);
    }
*/    

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
      // Save UI state changes to the savedInstanceState.
      // This bundle will be passed to onCreate if the process is
      // killed and restarted.
      super.onSaveInstanceState(savedInstanceState);
      savedInstanceState.putBoolean("isDataLoaded", true);
 
    }
    /*    
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
      super.onRestoreInstanceState(savedInstanceState);
      // Restore UI state from the savedInstanceState.
      // This bundle has also been passed to onCreate.
      boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
      double myDouble = savedInstanceState.getDouble("myDouble");
      int myInt = savedInstanceState.getInt("MyInt");
      String myString = savedInstanceState.getString("MyString");
    }
    */
    public void onStart() {
    	super.onStart();
    	Log.d(tag, "onStart() is called");
    }
    
    public void onStop() {
    	super.onStop();
    	Log.d(tag, "onStop() is called");
    }
    
    public void onRestart() {
    	super.onRestart();
    	Log.d(tag, "onRestart() is called");
    }
    public void onDestroy() {
    	super.onDestroy();
    	Log.d(tag, "onDestroy() is called");
    }
    public void onPause() {
    	super.onPause();
    	Log.d(tag, "onPause() is called");
    }
    
    public void onResume() {
    	super.onResume();
    	Log.d(tag, "onResume() is called");
    	
    	
    }
    
    Handler hRefresh1 = new Handler() {
		 public void handleMessage(Message msg) {
			// if (msg.what == 0) {
				 loadDialog.dismiss();
			// }
			 mapView.getOverlays().add(flagsOverlay);
/////////////////////////////////////////the following could be flagsOverlay.showDefaultBalloon()
			 
				BalloonOverlayView balloonView = flagsOverlay.getBalloonView();
		 		balloonView.setDefaultData(flags);
				MapView.LayoutParams params = new MapView.LayoutParams(
						LayoutParams.WRAP_CONTENT, 
						LayoutParams.WRAP_CONTENT, 
						flags.getFlagInfo().getGeoPoint(),
						MapView.LayoutParams.BOTTOM_CENTER);
				params.mode = MapView.LayoutParams.MODE_MAP;
				mapView.addView(balloonView, params);
				/////////////////////////////////////////
				
				mapView.getController().animateTo(flags.getFlagInfo().getGeoPoint());
				mapView.getController().setZoom(4);
			 
		 }
	 };
	    
	 private void loadDataAndOverlay() {
		 new Thread(new Runnable() {
			 public void run() {
					try {
						flags.loadData();
					} catch (IOException e) {
						e.printStackTrace();
					}
					 flagsOverlay.loadItemsOnce(); 
					 hRefresh1.sendEmptyMessage(0); 	
	            }
	        }).start();
	    }
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	Log.d(tag,"onCreate() is called");
    	loadDialog = ProgressDialog.show(this, "", "Loading Flags...", true);
    	
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        mapView = (MapView) findViewById(R.id.mapview);

         //Setup the zoom control
        mapView.setBuiltInZoomControls(true);
 		
        flagsContext = (FlagsContext)this.getApplicationContext();
        flags = flagsContext.getFlags();
        flagsOverlay = flagsContext.getFlagsOverlay();
        flagsOverlay.init(this);
		
    	//if (savedInstanceState == null || !savedInstanceState.containsKey("isDataLoaded")) {
    		
		//if (savedInstanceState == null) {
		//	Log.d(tag, "is nulllllllllllllllllllllll");
			
			 // flagsOverlay = new FlagsBalloonItemizedOverlay(this.getResources().getDrawable(R.drawable.star), flagsContext)  
			
    	this.loadDataAndOverlay();
    		//savedInstanceState.putBoolean("isDataLoaded", true);
    	//} else this.loadOverlay(false);
		
		
		
		
       // flagsOverlay = flagsContext.getFlagsOverlay();
        
		//this is needed to be called to initialize balloonView
		
		
		
		
        //handleIntent(getIntent());        
    }//end of function
    
    @Override
    public void onNewIntent(Intent intent) {
    	Log.d(tag,"onNewIntent() is called");
        setIntent(intent);
        searchDialog = ProgressDialog.show(this, "", "Finding Location...", true);
        handleIntent(intent);
    }
    
    Handler hRefresh = new Handler(){
    	public void handleMessage(Message msg) {
    	   searchDialog.dismiss();
    	   if (msg.what == 0) {
    		   flagsOverlay.showBalloon();   
    	   }
    	  }
    };
    	
    private void handleIntent(Intent intent) {
    	Log.d(tag,"handleIntent() is called");
    	
    	if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        	String query = intent.getStringExtra(SearchManager.QUERY);
        	//do search
        	this.findPlace(query,this.getResources());
        	 
        }
    }
    
    private void findPlace(final String query, final Resources res) {
    	new Thread(new Runnable() {
            public void run() {
               	 if (flags.findPlaceAndFillFlagInfo(query, res)) {
               		 hRefresh.sendEmptyMessage(0);
               	 } else {
               		 hRefresh.sendEmptyMessage(1);
               	 }
            }
        }).start();
    }
    
    @Override
    public boolean onSearchRequested() {
    	Log.d(tag,"onSearchRequested() is called");
    	flagsOverlay.getBalloonView().setVisibility(View.INVISIBLE);
    	return super.onSearchRequested();
    }
    
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
}